from flask import Blueprint, render_template, request
from app.models import Post, Category
from app.utils.helpers import process_html_content, process_straight_content

blog_bp = Blueprint('blog', __name__)

@blog_bp.route('/index')
def blog_index():
    page = request.args.get('page', 1, type=int)
    pagination = Post.query.order_by(Post.timestamp.desc()).paginate(page=page, per_page=6)
    posts = pagination.items
    for post in posts:
        post.formatted_content = process_straight_content(post.content)

    return render_template('blog/index.html', posts=posts, pagination=pagination)

@blog_bp.route('/post/<int:post_id>')
def post_detail(post_id):
    post = Post.query.get_or_404(post_id)
    if post.content:
        post.formatted_content = process_html_content(post.content)
    return render_template('blog/post_detail.html', post=post)

@blog_bp.route('/category/<int:category_id>')
def category_posts(category_id):
    page = request.args.get('page', 1, type=int)
    category = Category.query.get_or_404(category_id)
    # 获取该分类下的所有文章
    pagination  = category.posts.order_by(Post.timestamp.desc()).paginate(page=page, per_page=6)

    posts = pagination.items
    for post in posts :
        post.formatted_content = process_straight_content(post.content)

    return render_template('blog/index.html', category=category, posts=posts, pagination=pagination)